<?php
namespace app\index\controller;

use think\Controller;

/**
 * 最基础的Excel处理器 - 避免Response问题
 */
class ExcelProcessorBasic extends Controller
{
    /**
     * 最简单的处理方法
     */
    public function processExcelData()
    {
        // 直接输出JSON，避免使用ThinkPHP的json()方法
        header('Content-Type: application/json; charset=utf-8');

        try {
            $result = [
                'code' => 200,
                'msg' => '基础处理完成',
                'data' => [
                    'categories_processed' => 0,
                    'symptoms_processed' => 0,
                    'formulas_processed' => 0,
                    'test_info' => '这是一个基础测试响应'
                ]
            ];

            // 直接输出JSON，不使用ThinkPHP的响应类
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
            exit;

        } catch (\Exception $e) {
            $error = [
                'code' => 500,
                'msg' => '处理失败: ' . $e->getMessage(),
                'data' => null
            ];

            echo json_encode($error, JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    /**
     * 测试Excel文件读取
     */
    public function testExcelRead()
    {
        header('Content-Type: application/json; charset=utf-8');

        try {
            // 尝试使用PHPSpreadsheet读取Excel
            if (!class_exists('\PhpOffice\PhpSpreadsheet\IOFactory')) {
                echo json_encode([
                    'code' => 500,
                    'msg' => 'PHPSpreadsheet未安装',
                    'data' => null
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }

            $excelPath = 'F:/phpstudy_pro/intvale/ai_1/doc/sbb.xlsx';

            if (!file_exists($excelPath)) {
                echo json_encode([
                    'code' => 404,
                    'msg' => 'Excel文件不存在',
                    'data' => ['path' => $excelPath]
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($excelPath);
            $worksheet = $spreadsheet->getActiveSheet();
            $highestRow = $worksheet->getHighestRow();

            $sampleData = [];
            for ($row = 1; $row <= min(5, $highestRow); $row++) {
                $sampleData[] = [
                    'row' => $row,
                    'A' => (string)$worksheet->getCell('A' . $row)->getValue(),
                    'B' => (string)$worksheet->getCell('B' . $row)->getValue(),
                    'C' => (string)$worksheet->getCell('C' . $row)->getValue(),
                    'D' => (string)$worksheet->getCell('D' . $row)->getValue()
                ];
            }

            echo json_encode([
                'code' => 200,
                'msg' => 'Excel读取成功',
                'data' => [
                    'file_path' => $excelPath,
                    'total_rows' => $highestRow,
                    'sample_data' => $sampleData
                ]
            ], JSON_UNESCAPED_UNICODE);
            exit;

        } catch (\Exception $e) {
            echo json_encode([
                'code' => 500,
                'msg' => 'Excel读取失败: ' . $e->getMessage(),
                'data' => null
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    /**
     * 尝试数据库连接测试
     */
    public function testDatabase()
    {
        header('Content-Type: application/json; charset=utf-8');

        try {
            // 尝试数据库连接
            $result = \think\Db::query('SELECT 1 as test');

            echo json_encode([
                'code' => 200,
                'msg' => '数据库连接成功',
                'data' => [
                    'connection' => 'success',
                    'test_result' => $result
                ]
            ], JSON_UNESCAPED_UNICODE);
            exit;

        } catch (\Exception $e) {
            echo json_encode([
                'code' => 500,
                'msg' => '数据库连接失败: ' . $e->getMessage(),
                'data' => null
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    /**
     * 实际的Excel数据处理
     */
    public function processRealExcel()
    {
        header('Content-Type: application/json; charset=utf-8');

        try {
            // 读取Excel
            $excelPath = 'F:/phpstudy_pro/intvale/ai_1/doc/sbb.xlsx';
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($excelPath);
            $worksheet = $spreadsheet->getActiveSheet();
            $highestRow = $worksheet->getHighestRow();

            $result = [
                'categories_processed' => 0,
                'symptoms_processed' => 0,
                'formulas_processed' => 0,
                'errors' => []
            ];

            // 简单处理前几行数据
            for ($row = 2; $row <= min(6, $highestRow); $row++) {
                $formulaName = trim((string)$worksheet->getCell('A' . $row)->getValue());
                $mainSymptoms = trim((string)$worksheet->getCell('B' . $row)->getValue());
                $sideSymptoms = trim((string)$worksheet->getCell('C' . $row)->getValue());
                $categories = trim((string)$worksheet->getCell('D' . $row)->getValue());

                if (!empty($formulaName)) {
                    // 这里只是模拟处理，不实际写入数据库
                    $result['formulas_processed']++;

                    // 记录处理的数据
                    $result['processed_data'][] = [
                        'row' => $row,
                        'formula' => $formulaName,
                        'main_symptoms' => $mainSymptoms,
                        'side_symptoms' => $sideSymptoms,
                        'categories' => $categories
                    ];
                }
            }

            echo json_encode([
                'code' => 200,
                'msg' => '基础Excel处理完成',
                'data' => $result
            ], JSON_UNESCAPED_UNICODE);
            exit;

        } catch (\Exception $e) {
            echo json_encode([
                'code' => 500,
                'msg' => '处理失败: ' . $e->getMessage(),
                'data' => null
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    /**
     * 测试页面
     */
    public function index()
    {
        echo "<!DOCTYPE html>";
        echo "<html lang='zh-CN'>";
        echo "<head><meta charset='UTF-8'><title>基础Excel处理测试</title>";
        echo "<style>";
        echo "body { font-family: Arial, sans-serif; margin: 40px; }";
        echo ".btn { display: inline-block; padding: 10px 20px; margin: 10px; background: #007bff; color: white; text-decoration: none; border: none; border-radius: 5px; cursor: pointer; }";
        echo ".btn:hover { background: #0056b3; }";
        echo ".result { margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 5px; }";
        echo "</style>";
        echo "</head>";
        echo "<body>";
        echo "<h1>基础Excel处理测试</h1>";
        echo "<p>这个版本避免使用ThinkPHP的Response类，直接输出JSON</p>";

        echo "<button class='btn' onclick=\"testApi('/index/excel_processor_basic/testDatabase')\">测试数据库连接</button>";
        echo "<button class='btn' onclick=\"testApi('/index/excel_processor_basic/testExcelRead')\">测试Excel读取</button>";
        echo "<button class='btn' onclick=\"testApi('/index/excel_processor_basic/processExcelData')\">基础处理测试</button>";
        echo "<button class='btn' onclick=\"testApi('/index/excel_processor_basic/processRealExcel')\">实际Excel处理</button>";

        echo "<div id='result' class='result'>等待测试...</div>";

        echo "<script>";
        echo "function testApi(url) {";
        echo "  document.getElementById('result').innerHTML = '<p>处理中...</p>';";
        echo "  fetch(url, { method: 'POST' })";
        echo "    .then(response => response.text())";
        echo "    .then(text => {";
        echo "      try {";
        echo "        const data = JSON.parse(text);";
        echo "        document.getElementById('result').innerHTML = '<h3>结果:</h3><pre>' + JSON.stringify(data, null, 2) + '</pre>';";
        echo "      } catch(e) {";
        echo "        document.getElementById('result').innerHTML = '<h3>响应内容:</h3><pre>' + text + '</pre>';";
        echo "      }";
        echo "    })";
        echo "    .catch(error => {";
        echo "      document.getElementById('result').innerHTML = '<p style=\"color: red;\">请求失败: ' + error.message + '</p>';";
        echo "    });";
        echo "}";
        echo "</script>";

        echo "</body>";
        echo "</html>";
    }
}